package com.atguigu.yygh.cmn.service;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictListener dictListener;

    //根据数据id查询子数据列表
    //redis存储数据 名=dict::selectIndexList,值=List<Dict>
    //加上id 所以保证数据不会重复 解决只查看第一层
    @Cacheable(value = "dict", key = "'selectIndexList'+#id")
    @Override
    public List<Dict> findChildData(Long id) {
        //查询表数据
        QueryWrapper<Dict>wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //遍历判断有没有子数据
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }
    //导出字典表数据
    @Override
    public void exporData(HttpServletResponse response) {
        try {
            //1设置response参数
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //2.查询表获取数据
            List<Dict> dictList = this.list();
            //遍历集合，类型转换
            List<DictEeVo>dictEeVoList = new ArrayList<>();
            for (int i = 0; i < dictList.size(); i++) {
                Dict dict = dictList.get(i);
                DictEeVo dictEeVo = new DictEeVo();
                //dictEeVo.setId(dict.getId());
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVoList.add(dictEeVo);
            }
            //3.完成写操作
            EasyExcel.write(response.getOutputStream(),DictEeVo.class)
                    .sheet("数据字典").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException(20001,"到处字典表数据失败");
        }

    }
    //导入字典数据
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener)
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException(20001,"导入字典数据失败");
        }
    }
    //根据不同条件获取数据字典名称
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //判断parentDictCode是否有值，如果没值 一步查询
        //有值需要两步查询
        if (StringUtils.isEmpty(parentDictCode)){
            //如果没值 一步查询
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if (dict != null){
                return dict.getName();
            }
        }else {
            Dict parentDict = this.getDictByDictCode(parentDictCode);
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id",parentDict.getId())
                    .eq("value", value));
            if (dict != null){
                return dict.getName();
            }
        }
        return "";
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                .eq("dict_code", dictCode));
        List<Dict> dictList = this.findChildData(dict.getId());
        return dictList;
    }

    private Dict getDictByDictCode(String parentDictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",parentDictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }

    //判断有没有子数据
    private boolean isChildren(Long dictId) {
        QueryWrapper<Dict>wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",dictId);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
